package graphics;

import java.awt.Color;
import java.awt.geom.Rectangle2D;

import main.Game;

import ship.Ship;
import util.Point;

public class SquareButtonMatrix {
	int[][] pips = new int[5][5];
	Point cords;

	int sparePips = 0;
	Ship s;

	public SquareButtonMatrix(Ship s, Point p) {
		this.s = s;
		cords = p;
		for(int i = 0; i < pips.length; i++) {
			for(int j = 0; j < 2; j++) {
				pips[i][j] = 1;
			}
		}
	}

	public void draw(MaxGraphics g) {
		g.translate(cords.getX(), cords.getY());
		for(int i = 0; i < pips.length; i++) {
			for(int j = 0; j < pips.length; j++) {
				g.setColor(Color.black);
				g.drawRect(j * 30, i * 30, 20, 20);
				if(pips[i][j] == 1) {
					g.setColor(Color.GREEN);
					g.fillRect(j * 30, i * 30, 18, 18);
				}
			}
		}
		g.translate(-cords.getX(), -cords.getY());
	}

	
	
	public void handleClick(Point p) {
		int col = (int) (p.getX() / 30) - 1;
		int row = (int) (p.getY() / 30) - 1;
		if(row < 0 || row > 4 || col < 0 || col > 4) {
			return;
		}
		if(pips[row][col] == 1) {
			decPip(row);
		}
		else if(pips[row][col] == 0) {
			incPip(row);
		}
		notifyShip();
	}
	
	public void notifyShip() {
		int[] power = new int[pips[0].length];
		for(int i = 0; i < pips.length; i++) {
			for(int j = 0; j < pips[0].length; j++) {
				power[i] += pips[i][j];
			}
		}
		this.s.setPower(power);
	}

	public void decPip(int index) {
		for(int i = pips.length - 1; i >= 0; i--) {
			if(pips[index][i] == 1) {
				sparePips++;
				pips[index][i] = 0;
				return;
			}
		}
	}

	public void incPip(int index) {
		for(int i = 0; i < pips.length; i++) {
			if(pips[index][i] == 0) {
				if(sparePips > 0) {
					pips[index][i] = 1;
					sparePips--;
				}
				return;
			}
		}
	}
}
